﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using VkClientIM.Logic;

namespace VkClientIM.UI
{
	/// <summary>
	/// Interaction logic for AudioPlayer.xaml
	/// </summary>
	public partial class AudioPlayer : UserControl
	{
		private PlaylistViewModel _playlist = new PlaylistViewModel();
		private MediaElement _player;

		private DispatcherTimer _timer;
		public AudioPlayer()
		{
			InitializeComponent();
			_timer = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.Background,
															 OnTimer, Dispatcher);

			this.DataContext = _playlist;
		}
		
		private void OnTimer(object o,EventArgs e)
		{
			if (_player != null)
			{
				PlayProgress = _player.Position.TotalSeconds/((Logic.AudioRecord) playlist.SelectedItem).Duration*100;
			}
		}

		public void LoadPlaylist(AudioRecord[] records)
		{
			for (int i = 0; i < records.Length; i++)
			{
				_playlist.AddAudioRecord( records[i] );
			}
		}

		private void CreatePlayer(Uri source )
		{
			if (_player!=null)
			{
				_player.Stop();
				mediaRoot.Children.Remove(_player);
			}
			_player = null;
			_player = new MediaElement
			          	{
			          		LoadedBehavior = MediaState.Manual
			          	};
			_player.MediaEnded += new System.Windows.RoutedEventHandler(_player_MediaEnded);
			_player.Loaded += delegate
			                  	{
									_player.Play();
			                  	};
			_player.Source = source;
			mediaRoot.Children.Add(_player);
		}

		void _player_MediaEnded(object sender, System.Windows.RoutedEventArgs e)
		{
		}

		public PlaylistViewModel Playlist
		{
			get { return _playlist; }
		}

		public static DependencyProperty PlayProgressProperty = DependencyProperty.Register(
			"PlayProgress", typeof(double), typeof(AudioPlayer));

		public double PlayProgress
		{
			get { return (double)GetValue(PlayProgressProperty); }
			set{SetValue(PlayProgressProperty,value);}
		}

		private void playlist_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			Logic.AudioRecord audioRecord = (Logic.AudioRecord)e.AddedItems[0];
			Dispatcher.Invoke(new Action<Uri>(this.CreatePlayer), audioRecord.Url);
		}
	}
}
